package demo6;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

class Request{
    public String username;
    public String password;
}

class Response{
    public boolean ok;
}

@WebServlet("/demo6")
public class Test extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ObjectMapper mapper = new ObjectMapper();

        //json字符串映射成为java对象
        Request request = mapper.readValue(req.getInputStream(), Request.class);
        System.out.println("username: " + request.username);
        System.out.println("password: " + request.password);
        Response response = new Response();
        response.ok=true;

        //下面的这个代码就是readvalue的反向操作：java对象---》json字符串
        String respJson = mapper.writeValueAsString(response);
        resp.setContentType("application/json; charset=utf-8");
        resp.getWriter().write(respJson);
    }
}
